import sys
from bs4 import BeautifulSoup
import json
import re
def clean_name(name):
"""Очищает имя от лишних пробелов и переносов"""
if not name:
return name
# Убираем переносы строк
cleaned = name.replace('\n', ' ')
# Заменяем множественные пробелы на один
cleaned = re.sub(r'\s+', ' ', cleaned)
# Убираем пробелы в начале и конце
return cleaned.strip()
def parse_nodes(input_file, output_file):
# Чтение HTML из файла
try:
with open(input_file, 'r', encoding='utf-8') as f:
html_content = f.read()
except FileNotFoundError:
print(f"❌ Файл {input_file} не найден")
return
except Exception as e:
print(f"❌ Ошибка чтения файла {input_file}: {e}")
return
# Парсим HTML
soup = BeautifulSoup(html_content, 'html.parser')
nodes = []
# Ищем все div с атрибутом data-keyboard-nav-type="action"
items = soup.find_all('div', {'data-keyboard-nav-type': 'action'})
# Рассчитываем позиции: сетка 15x15 с шагом 192 пикселя
for index, item in enumerate(items):
try:
# Извлечение имени
name_tag = item.find('span', {'data-test-id': 'node-creator-item-name'})
raw_name = name_tag.get_text() if name_tag else None
# Очищаем имя от лишних пробелов и переносов
name = clean_name(raw_name)
# Извлечение типа из атрибута data-keyboard-nav-id
full_type = item.get('data-keyboard-nav-id')
if name and full_type:
# Разделяем тип и ID
match = re.match(r'^(.+)-([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$', full_type)
if match:
node_type = match.group(1)
node_id = match.group(2)
else:
node_type = full_type
node_id = "00000000-0000-0000-0000-000000000000"
# Рассчитываем позицию: сетка 15x15
row = index // 15 # Номер строки (каждые 15 элементов спускаемся вниз)
col = index % 15 # Номер столбца (0-14)
x_position = col * 192
y_position = row * 192
node = {
"parameters": {},
"name": name,
"type": node_type,
"typeVersion": 1,
"position": [x_position, y_position],
"id": node_id
}
nodes.append(node)
except Exception as e:
print(f"⚠️ Ошибка при обработке элемента: {e}")
# Формируем итоговую структуру
result = {
"nodes": nodes,
"connections": {}
}
# Сохраняем в JSON
try:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
print(f"✅ Успешно извлечено {len(nodes)} узлов. Результат записан в {output_file}")
except Exception as e:
print(f"❌ Ошибка записи файла {output_file}: {e}")
def main():
if len(sys.argv) != 3:
print("Использование: python parse_nodes.py <input_file.html> <output_file.json>")
sys.exit(1)
input_filename = sys.argv[1]
output_filename = sys.argv[2]
parse_nodes(input_filename, output_filename)
if __name__ == "__main__":
main()